import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;


import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;

public class FlightInfoClient implements FlightInfoMsgs{

	/**
	 * The service type to browse for. This should be the same as the one you use
	 * to register services with.
	 */
	public static final String SERVICE_TYPE = "GroupD._udp.local.";
	
	private static final String FORMAT_ERROR = "Formatting error in reply from server. Please try again...";
	private static final String INCORRECT_MSG = "Incorrect message received from server. Please try again...";
	private static final String INVALID_CMD_LINE_OPT = "\nWarning! You must choose from the available options only.";
	
	private String host;
	private int port;

	 public static boolean terminateRequested=false;
	/**
	 * This class implements the ServiceListener interface which receives
	 * notifications when services are discovered and lost. Note that in your
	 * implementations the listener will probably form part of another class; not
	 * a static, stand-alone class like this. Think about how you might add
	 * listeners in the Swing framework for example.
	 */
	class SampleListener implements ServiceListener {
		public void serviceAdded(final ServiceEvent event) {
			System.out.println("Service added   : " + event.getName() + "."
					+ event.getType());
			// The following line is required to get all information associated
			// with a service registration - not just the name and type - for
			// example, the port number and properties. Notification is sent to the
			// serviceResolved(...) method which the request has been completed.
			event.getDNS().requestServiceInfo(event.getType(), event.getName(), 0);
		}

		public void serviceRemoved(ServiceEvent event) {
			System.out.println("Service removed : " + event.getName() + "."
					+ event.getType());
			host = null;
		}

		public void serviceResolved(ServiceEvent event) {
			System.out.println("Service resolved: " + event.getInfo().getName()
					+ ", host: " + event.getInfo().getHostAddress() + ", port: "
					+ event.getInfo().getPort());
			
		
			

			setHost(event.getInfo().getHostAddress());
			setPort(event.getInfo().getPort());
		}
	}

	public FlightInfoClient(JmDNS jmDns) {

		// Work the magic: this is where the service listener is registered.
		jmDns.addServiceListener(SERVICE_TYPE, new SampleListener());
	}

	synchronized private String getHost() {
		return host;
	}

	synchronized private int getPort() {
		return port;
	}

	synchronized private void setHost(String host) {
		this.host = host;
	}

	synchronized private void setPort(int port) {
		this.port = port;
	}


		
		
	
	/**
	 * Creates a connection to the server and sends a message.
	 * 
	 * @param a_message
	 *          the message to send to the server.
	 */
	public String sendMessage(String a_message) {
		try {
			
			String reply = null;
			
			// Create a connection to the server.
			Socket toServer = new Socket(host, port);

			PrintWriter out = new PrintWriter(toServer.getOutputStream(), true);

			// Write the message to the socket.
			out.println(a_message);

			BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
			reply = in.readLine();
			System.out.println("Your Flight Arrival Details:\n" +reply);

			// tidy up
			in.close();
			out.close();
			toServer.close();
			return reply;
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SecurityException se) {
			se.printStackTrace();
		}
		return null;
	}

	private void processListReply(String reply){
		int currDelim = 0;
		int numOutlets = 0;
		String leftToParse = reply;
		String field = null;

	}
	
	
		
	public static void main(String[] args) throws IOException, InterruptedException {
	
		
		
		final JmDNS jmdns = JmDNS.create();
		
		 
		FlightInfoClient client = new FlightInfoClient(jmdns);

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String cmdln_in = null;
		  int choice = 0;
		  
		
		// main loop catering for command line i/o
		MAIN_LOOP:
		
		while (true) {
			System.out.println("*********************FLIGHT INFO CLIENT HAS BEEN STARTED**********************************************************************");
		     System.out
             .println("\n\n1. Arrivals\n2. Departures\n3. Search by Destination, Airline, Flight No.,  Date, or Time.\nPlease choose option 1,2,3:");
		       int end = 0;

	Scanner sc = new Scanner(System.in);
     choice = sc.nextInt();

     if (choice == 1) {
         try {
             System.out.println("What is the flight number of the arrival?");
			cmdln_in = in.readLine();
			cmdln_in = cmdln_in.trim();
		
			String reply = null;
			reply = client.sendMessage(cmdln_in);//FR117
			if (reply != null)
			client.processListReply(reply);
			break;
         } catch (IOException ioe) {
         }
     }
     if (choice == 2) {
         try {
             System.out.println("What is the flight number of the Departure?");
			cmdln_in = in.readLine();
			cmdln_in = cmdln_in.trim();
			String reply = null;
			reply = client.sendMessage(cmdln_in);//FR117
			if (reply != null)
			client.processListReply(reply);
			break;
         } catch (IOException ioe) {
         }
     }
     if (choice == 3) {
         try {
             System.out
             .println("Please enter Destination/Origin, Airline, Flight No.,  Date, or Time.");
			cmdln_in = in.readLine();
			cmdln_in = cmdln_in.trim();
			String reply = null;
			reply = client.sendMessage(cmdln_in);//FR117
			if (reply != null)
			client.processListReply(reply);
			break;
         } catch (IOException ioe) {
         }
     }
    	 
		
		in.close();
		jmdns.close();
		System.exit(0);
	}
	
	}
	
	}



